<template>
    <div>
        <a-modal title="设置模板" centered v-model:visible="innerVisible" :width="1000" :bodyStyle="{ height: '600px', overflow: 'auto' }" okText="保存" @ok="handleSave" @cancel="handleCancel">
            <a-form layout="inline" ref="ruleFormRef" :model="form" :rules="rules">
                <a-row>
                    <a-col :span="16">
                        <a-form-item label="模板名称" :span="24" name="tempName">
                            <a-input v-model:value="form.tempName" allowClear :maxlength="33" placeholder="请输入" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
            <h-section title="选择系统" collapse style="padding-bottom: 0">
                <a-checkbox-group style="width: 100%" v-model:value="checkedSystemList">
                    <a-row>
                        <a-col :span="6" v-for="item of isShowMoreSystemBtn && !systemCollapse ? systemOptions.slice(0, 8) : systemOptions" :key="item.id">
                            <a-checkbox :value="item.id" v-fitText style="width: 100%"> {{ item.systemName }} </a-checkbox>
                        </a-col>
                    </a-row>
                </a-checkbox-group>
                <flexbox justify="flex-end" style="cursor: pointer" @click="systemCollapse = !systemCollapse" v-if="isShowMoreSystemBtn">
                    <a class="font-s-base">{{ systemCollapse ? '收起' : '展开' }}</a>
                    <UpOutlined class="font-s-base primary-color" style="margin-left: 4px" v-if="systemCollapse" />
                    <DownOutlined class="font-s-base primary-color" style="margin-left: 4px" v-else />
                </flexbox>
            </h-section>
            <h-section title="设置字段" collapse style="padding-top: 0">
                <div v-for="(item, index) in settingObj" :key="index">
                    <h5>{{ item.title }}</h5>
                    <a-checkbox-group style="width: 100%" v-model:value="item.checkedList">
                        <a-row>
                            <a-col :span="4" v-for="item of !item.btnCollapse ? item.options.slice(0, 6) : item.options" :key="item.code">
                                <a-checkbox :value="item">
                                    {{ item }}
                                </a-checkbox>
                            </a-col>
                        </a-row>
                    </a-checkbox-group>
                    <flexbox justify="flex-end" style="cursor: pointer" @click="item.btnCollapse = !item.btnCollapse">
                        <a class="font-s-base">{{ item.btnCollapse ? '收起' : '展开' }}</a>
                        <UpOutlined class="font-s-base primary-color" style="margin-left: 4px" v-if="item.btnCollapse" />
                        <DownOutlined class="font-s-base primary-color" style="margin-left: 4px" v-else />
                    </flexbox>
                </div>
            </h-section>
            <h-section title="设置范围" collapse>
                <a-radio-group v-model:value="form.period">
                    <a-radio v-for="item of timeRangeOptions" :key="item.value" :value="item.value">
                        {{ item.title }}
                    </a-radio>
                </a-radio-group>
            </h-section>
        </a-modal>
    </div>
</template>

<script lang="ts">
import api from '@/api';
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue/es';
import { defineComponent, ref, unref, reactive, toRefs, computed, nextTick } from 'vue';
export default defineComponent({
    components: {
        DownOutlined,
        UpOutlined
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        detail: {
            type: Object,
            default: () => ({})
        },
        info: {
            type: Object,
            default: () => ({})
        }
    },
    emits: ['update:visible', 'success'],
    setup(props, { emit }) {
        const ruleFormRef = ref<any>();
        const validateRepeatName = async (rule: any, value: any) => {
            if (value) {
                const query = {
                    tempName: state.form.tempName,
                    id: state.form.id,
                    fsAccountId: props.info.id
                };
                const { success } = await api.feishuModel.validFieldRepeat(query, { cancelDuplicated: true });
                return success ? Promise.reject('模板名称不能相同') : Promise.resolve();
            }
        };
        const rules = {
            tempName: [
                { required: true, message: '模板名称不能为空', trigger: 'blur' },
                { required: true, validator: validateRepeatName }
            ]
        };
        const state = reactive<any>({
            innerVisible: false,
            mySystem: [],
            checkedSystemList: [],
            isShowMoreSystemBtn: false, // 是否显示更多按钮
            systemCollapse: false, // 是否已经点击展开按钮
            form: {
                tempName: '',
                period: 1,
                id: null
            },
            settingObj: {
                business: {
                    title: '业务需求表',
                    options: ['系统', '业务需求名称', '业务需求描述', '发起人', '发起人部门', '标签', '阶段', '状态', '优先级', '预计结束时间'],
                    checkedList: ['系统', '业务需求名称', '业务需求描述', '发起人', '发起人部门'],
                    btnCollapse: false
                },
                product: {
                    title: '产品需求表',
                    options: ['系统', '产品需求名称', '产品需求描述', '创建人', '创建时间', '需求类型', '标签', '优先级', '阶段', '预发布版本号', '预计交付时间', '预估点(SP)', '计划工时(h)'],
                    checkedList: ['系统', '产品需求名称', '产品需求描述', '创建人', '创建时间'],
                    btnCollapse: false
                },
                version: {
                    title: '预发布版本',
                    options: ['系统', '预发布版本号', '预发布版本名称', '预计交付时间', '开始时间', '上线时间', '创建人', '状态', '流程状态'],
                    checkedList: ['系统', '预发布版本号', '预发布版本名称', '预计交付时间', '创建人'],
                    btnCollapse: false
                }
            },
            timeRangeOptions: [
                {
                    title: '一月内',
                    value: 1
                },
                {
                    title: '二月内',
                    value: 2
                },
                {
                    title: '三月内',
                    value: 3
                }
            ],
            periodCheckedList: []
        });
        const systemOptions = computed(() => {
            state.isShowMoreSystemBtn = state.mySystem.length > 8;
            return state.mySystem.map((item) => ({
                ...item,
                checked: false
            }));
        });
        const init = () => {
            getSystemOptions();
            state.innerVisible = true;
            nextTick(() => {
                unref(ruleFormRef).clearValidate();
            });
            if (props.detail.id) {
                Object.keys(state.form).forEach((key) => {
                    state.form[key] = props.detail[key];
                });
                const { systemList, businessList, productList, versionList } = props.detail;
                state.checkedSystemList = systemList.split(',').map((item) => +item);
                state.settingObj.business.checkedList = businessList.split(',');
                state.settingObj.product.checkedList = productList.split(',');
                state.settingObj.version.checkedList = versionList.split(',');
            }
        };
        const getSystemOptions = async () => {
            const query = {
                position: '产品经理'
            };
            const { success, moule } = await api.systemManagerModel.findByEmpIdAndPosition(query);
            if (success) {
                state.mySystem = [...moule];
            }
        };
        const handleSave = () => {
            unref(ruleFormRef)
                .validate()
                .then(async () => {
                    if (!state.checkedSystemList.length) {
                        message.error('系统不能为空');
                        return;
                    }
                    if (!state.settingObj.business.checkedList.length) {
                        message.error('请至少勾选一个业务需求表');
                        return;
                    }
                    if (!state.settingObj.product.checkedList.length) {
                        message.error('请至少勾选一个产品需求表');
                        return;
                    }
                    if (!state.settingObj.version.checkedList.length) {
                        message.error('请至少勾选一个预发布版本');
                        return;
                    }
                    const query = {
                        ...state.form,
                        systemList: state.checkedSystemList.join(','),
                        businessList: state.settingObj.business.checkedList.join(','),
                        productList: state.settingObj.product.checkedList.join(','),
                        versionList: state.settingObj.version.checkedList.join(',')
                    };
                    const { success, errorMsg } = await api.feishuModel.saveTempInfo(query);
                    if (success) {
                        message.success(state.form.id ? '修改成功' : '新增成功');
                        emit('success');
                    } else {
                        message.error(errorMsg);
                    }
                    handleCancel();
                });
        };
        const handleCancel = () => {
            state.innerVisible = false;
            setTimeout(() => {
                emit('update:visible', false);
            }, 500);
        };
        init();
        return {
            ruleFormRef,
            rules,
            ...toRefs(state),
            systemOptions,
            handleSave,
            handleCancel
        };
    }
});
</script>

<style scoped>
</style>